package com.dstz.form.util.tableexcel.column;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dstz.bus.api.constant.BusColumnCtrlType;
import com.dstz.bus.api.model.IBusinessColumn;

import cn.hutool.core.util.StrUtil;

/**
 * <pre>
 * 下拉框的类型转化
 * </pre>
 * 
 * @author aschs
 * @date 2019年9月9日
 * @owner 大世同舟
 */
@Service
public class SelectExcellor extends BusinessColumnExcellor {

	@Override
	BusColumnCtrlType getCtrlType() {
		return BusColumnCtrlType.SELECT;
	}

	@Override
	Object fromExcel(IBusinessColumn column, Object text, JSONObject config) {
		String[] ts = new String[] { text.toString() };
		if (this.getCtrlType() == BusColumnCtrlType.CHECKBOX) {
			ts = text.toString().split(",");
		}
		List<String> ls = new ArrayList<>();
		if (!config.containsKey("options")) {
			return text;
		}
		JSONArray options = config.getJSONArray("options");
		for (String t : ts) {
			boolean exist = false;
			for (int i = 0; i < options.size(); i++) {
				JSONObject op = options.getJSONObject(i);
				if (op.getString("txt").equals(t)) {
					exist = true;
					ls.add(op.getString("key"));
				}
			}
			if (!exist) {
				ls.add(t);
			}
		}
		return StrUtil.join(",", ls.toArray());
	}

	@Override
	Object toExcel(IBusinessColumn column, Object value, JSONObject config) {
		String[] vs = new String[] { value.toString() };
		if (this.getCtrlType() == BusColumnCtrlType.CHECKBOX) {
			vs = value.toString().split(",");
		}
		List<String> ls = new ArrayList<>();
		if (!config.containsKey("options")) {
			return value;
		}
		JSONArray options = config.getJSONArray("options");
		for (String v : vs) {
			boolean exist = false;
			for (int i = 0; i < options.size(); i++) {
				JSONObject op = options.getJSONObject(i);
				if (op.getString("key").equals(v)) {
					exist = true;
					ls.add(op.getString("txt"));
				}
			}
			if (!exist) {
				ls.add(v);
			}
		}
		return StrUtil.join(",", ls.toArray());
	}

}
